#include "displayController.h"
#include <Arduino.h>

#define WIFI_SSID "helloworld"
#define WIFI_PASSWORD "12345678"

DisplayController::DisplayController()
    : led(LED_PIN),     // 初始化 LED 引脚
      server(PORT)      // 初始化 WiFiServer 端口
{
    // screen 和 wifi 使用默认构造函数即可
}

/**
 * 初始化 DisplayController：LED、屏幕、WiFi、Server
 */
void DisplayController::setup() {
    Serial.begin(115200);

    // LED 初始化
    led.on();  // 默认点亮

    // 屏幕初始化
    screen.setup();
    screen.showStartupMessage("hello esp32");

    // WiFi 连接
    wifi.connect(WIFI_SSID, WIFI_PASSWORD);

    // 启动 WiFi Server
    server.begin();
}

/**
 * 循环处理投屏数据
 */
void DisplayController::loop() {
    static bool wasConnected = false;
    bool isConnected = client && client.connected();

    if (!isConnected) {
        delay(500);
        if (wasConnected != isConnected) Serial.println("等待连接中...");
        client = server.available();
        isConnected = client && client.connected();
        if (isConnected) Serial.println("客户端已连接！");
    } else {
        // 处理屏幕显示
        screen.displayBlock(client);
    }

    wasConnected = isConnected;
}